﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
using DocumentFormat.OpenXml.Wordprocessing;
using Spire.DocViewer.Forms;
using WordOpenXmlClassLibrary;
using WordOpenXmlClassLibrary.Entity;
using WordOpenXmlClassLibrary.Enum;
using WordOpenXmlClassLibrary.Utils;

namespace WordOpenXmlFormApp
{

    public partial class ApplicationForm : Form
    {
        bool debug = true;
        // 定义
        Dictionary<string, BlockOption> blockOptionDictionary = new Dictionary<string, BlockOption>();
        BlockOption currentOption = new BlockOption();
        String currentNodeKey = ""; // 当前节点Key

        TreeNode preNode; // 前置节点
        TreeNode nextNode; // 后置节点
        TreeNode currentNode; // 当前节点
        string nodeText;
        string nodeTag;

        private int ZoomNum = 100;

        public ApplicationForm()
        {
            InitializeComponent();
        }


        private void ShowLoadProgressBar()
        {
            toolStripProgressBar.Maximum = 100;//设置最大长度值
            toolStripProgressBar.Value = 0;//设置当前值
            toolStripProgressBar.Step = 20;//设置没次增长多少
            toolStripProgressBar.Visible = true;
            for (int i = 0; i < 5; i++)//循环
            {
                System.Threading.Thread.Sleep(100);//暂停1秒
                toolStripProgressBar.Value += toolStripProgressBar.Step; //让进度条增加一次
            }
        }

        private void ButtonExit_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否确定退出?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                System.Environment.Exit(0);
            }
        }

        private void ComboBoxPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (comboBoxPageSize.SelectedIndex)
            {
                case (int)PageSizeValues.A3:
                    comboBoxPageOrientation.SelectedIndex = (int)PageOrientationValues.Portrait;
                    break;
                case (int)PageSizeValues.A4:
                    comboBoxPageOrientation.SelectedIndex = (int)PageOrientationValues.Landscape;
                    break;
            }
        }

        private void TabControl_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (this.tabControl.SelectedIndex)
            {
                case 0:
                    break;
                case 1:
                    //string filepath = toolStripStatusLabelTip.Text;
                    //LoadFromViewFile(filepath);
                    break;
            }

        }

        private void LoadFromViewFile(string filepath)
        {
            try
            {
                this.ZoomNum = 100;
                // Load doc document from file 
                this.docDocumentViewer.LoadFromFile(filepath);
                this.docDocumentViewer.ZoomTo(ZoomNum);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void ButtonZoomToDown_Click(object sender, EventArgs e)
        {
            if (ZoomNum > 50)
            {
                ZoomNum = ZoomNum - 5;
                this.docDocumentViewer.ZoomTo(ZoomNum);
            }
            else
            {
                MessageBox.Show("已缩放到最小", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        private void ButtonZoomToUp_Click(object sender, EventArgs e)
        {
            if (ZoomNum <= 120)
            {
                ZoomNum = ZoomNum + 5;
                this.docDocumentViewer.ZoomTo(ZoomNum);
            }
            else
            {
                MessageBox.Show("已缩放到最大", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void ButtonExportFile_Click(object sender, EventArgs e)
        {
            string filepath = toolStripStatusLabelTip.Text;
            Process.Start("explorer.exe", filepath);
        }

        private void ApplicationForm_Load(object sender, EventArgs e)
        {

            this.comboBoxPageSize.SelectedIndex = (int)PageSizeValues.A4;
            this.comboBoxPageOrientation.SelectedIndex = (int)PageOrientationValues.Landscape;
            this.comboBoxObjectiveItemOrientation.SelectedIndex = (int)PageOrientationValues.Portrait;

            string[] items = { "考试名称", "学生信息", "准考证填涂" };
            for (int i = 0; i < items.Length; i++)
            {
                TreeNode treeNode = new TreeNode();
                string nodeId = Guid.NewGuid().ToString("N");
                treeNode.Tag = nodeId;
                treeNode.Text = items[i];
                treeViewBlock.Nodes.Add(treeNode);
            }
        }

        private void ButtonNodeUp_Click(object sender, EventArgs e)
        {
            currentNode = treeViewBlock.SelectedNode;
            string nodeKey = (string)currentNode.Tag;
            if (currentNode == null)
            {
                MessageBox.Show("请选择要上移的节点！");
            }
            else
            {
                if (blockOptionDictionary.ContainsKey(nodeKey))
                {
                    preNode = currentNode.PrevNode;
                    if (preNode == null)
                    {
                        MessageBox.Show("当前节点已到达顶部！");
                    }
                    else
                    {
                        nodeText = preNode.Text;
                        nodeTag = (string)preNode.Tag;
                        preNode.Text = currentNode.Text;
                        preNode.Tag = currentNode.Tag;
                        currentNode.Text = nodeText;
                        currentNode.Tag = nodeTag;
                        treeViewBlock.SelectedNode = currentNode.PrevNode;
                    }
                }
            }
        }

        private void ButtonNodeDown_Click(object sender, EventArgs e)
        {
            currentNode = treeViewBlock.SelectedNode;
            string nodeKey = (string)currentNode.Tag;
            if (currentNode == null)
            {
                MessageBox.Show("请选择要下移的节点！");
            }
            else
            {
                if (blockOptionDictionary.ContainsKey(nodeKey))
                {
                    nextNode = currentNode.NextNode;
                    if (nextNode == null)
                    {
                        MessageBox.Show("当前节点已到达底部！");
                    }
                    else
                    {
                        nodeText = nextNode.Text;
                        nodeTag = (string)nextNode.Tag;
                        nextNode.Text = currentNode.Text;
                        nextNode.Tag = currentNode.Tag;
                        currentNode.Text = nodeText;
                        currentNode.Tag = nodeTag;
                        treeViewBlock.SelectedNode = currentNode.NextNode;
                    }
                }
            }
        }
        private void ButtonObjectiveItem_Click(object sender, EventArgs e)
        {
            this.currentOption.BlockType = (int)BlockTypes.Objective;
            this.ToolStripStatusLabelDisplay();

            this.groupBoxOption.Text = this.buttonObjectiveItem.Text;
            this.panelOptionBlockObjectiveItem.Visible = true;

            this.panelOptionBlockSubjectiveItem.Visible = false;
            this.panelOptionBlockWritting.Visible = false;
        }

        private void ButtonSubjectiveItem_Click(object sender, EventArgs e)
        {
            this.currentOption.BlockType = (int)BlockTypes.Subjective;
            this.ToolStripStatusLabelDisplay();

            this.groupBoxOption.Text = this.buttonSubjectiveItem.Text;

            this.panelOptionBlockObjectiveItem.Visible = false;
            this.panelOptionBlockSubjectiveItem.Visible = true;
            this.panelOptionBlockWritting.Visible = false;
            this.panelOptionBlockObjectiveItemBold.Visible = true;
        }

        private void ButtonEnglishWriting_Click(object sender, EventArgs e)
        {
            this.currentOption.BlockType = (int)BlockTypes.English;
            this.ToolStripStatusLabelDisplay();


            this.groupBoxOption.Text = this.buttonEnglishWriting.Text;
            this.panelOptionBlockWritting.Visible = true;
            this.panelOptionBlockSubjectiveItem.Visible = true;
            this.panelOptionBlockObjectiveItem.Visible = false;
            this.panelOptionBlockObjectiveItemBold.Visible = false;
            this.numericUpDownWordCount.Visible = false;
        }

        private void ButtonChineseWriting_Click(object sender, EventArgs e)
        {
            this.currentOption.BlockType = (int)BlockTypes.Chinese;
            this.ToolStripStatusLabelDisplay();

            this.groupBoxOption.Text = this.buttonChineseWriting.Text;
            this.panelOptionBlockWritting.Visible = true;
            this.panelOptionBlockSubjectiveItem.Visible = true;
            this.panelOptionBlockObjectiveItem.Visible = false;
            this.panelOptionBlockObjectiveItemBold.Visible = false;
            this.numericUpDownWordCount.Visible = true;
        }

        private void ButtonNodeDelete_Click(object sender, EventArgs e)
        {
            currentNode = treeViewBlock.SelectedNode;
            string nodeKey = (string)currentNode.Tag;
            if (currentNode == null)
            {
                MessageBox.Show("请选择要删除的节点！");
            }
            else
            {
                if (blockOptionDictionary.ContainsKey(nodeKey))
                {
                    if (MessageBox.Show("是否确定删除节点\n'" + currentNode.Text + "'", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                    {
                        treeViewBlock.SelectedNode.Remove();
                    }
                }
            }
        }

        private void ButtonAddNodeBlock_Click(object sender, EventArgs e)
        {
            this.InitForm();

            string titleName = textBoxBlockNameTitle.Text;
            bool titleCenter = checkBoxBlockNameTitleCenter.Checked;

            // 生成NodeKey
            this.currentNodeKey = Guid.NewGuid().ToString("N");
            this.ToolStripStatusLabelDisplay();
            // 可见性设置
            this.groupBoxOption.Visible = true;
            this.panelOptionBlockWritting.Visible = false;
            this.panelOptionBlockObjectiveItem.Visible = false;
            this.panelOptionBlockSubjectiveItem.Visible = false;
            this.panelOptionBlockObjectiveItemBold.Visible = false;
            this.groupBoxOption.Text = this.buttonAddNodeBlock.Text;
            this.groupBoxBlockType.Enabled = true;

            this.currentOption = new BlockOption();
        }



        private void ButtonBlockOptionSave_Click(object sender, EventArgs e)
        {

            string titleName = textBoxBlockNameTitle.Text.Trim();


            if (string.IsNullOrEmpty(titleName))
            {
                MessageBox.Show("请输入题目标题，内容不能为空！");
                textBoxBlockNameTitle.Focus();
            }
            else
            {
                if (MessageBox.Show("是否确定保存题目信息?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    // 隐藏操作区域
                    groupBoxOption.Visible = false;

                    this.AddOptionItem();

                    if (blockOptionDictionary.ContainsKey(currentNodeKey))
                    {
                        treeViewBlock.SelectedNode.Text = titleName;

                        // 存储到字典中
                        blockOptionDictionary[currentNodeKey] = currentOption;
                    }
                    else
                    {
                        TreeNode treeNode = new TreeNode();
                        treeNode.Text = titleName;
                        treeNode.Tag = currentNodeKey;
                        treeViewBlock.Nodes.Add(treeNode);

                        // 存储到字典中
                        blockOptionDictionary.Add(currentNodeKey, currentOption);
                    }
                }
            }
        }



        private void PanelOptionBlockWritting_VisibleChanged(object sender, EventArgs e)
        {
            panelSpan1.Visible = panelOptionBlockWritting.Visible;
        }

        private void PanelOptionBlockObjectiveItem_VisibleChanged(object sender, EventArgs e)
        {
            panelSpan2.Visible = panelOptionBlockObjectiveItem.Visible;
        }

        private void PanelOptionBlockSubjectiveItem_VisibleChanged(object sender, EventArgs e)
        {
            panelSpan3.Visible = panelOptionBlockSubjectiveItem.Visible;
            panelOptionBlockObjectiveItemBold.Visible = panelOptionBlockSubjectiveItem.Visible;
        }

        private void PanelOptionBlockObjectiveItemBold_VisibleChanged(object sender, EventArgs e)
        {
            panelSpan4.Visible = panelOptionBlockObjectiveItemBold.Visible;
        }

        private void NumericUpDownWordCount_VisibleChanged(object sender, EventArgs e)
        {
            this.labelBlockOptionWordCount.Visible = this.numericUpDownWordCount.Visible;
        }

        /// <summary>
        /// 新增设置项
        /// </summary>
        private void AddOptionItem()
        {
            string titleName = textBoxBlockNameTitle.Text.Trim();
            bool titleCenter = checkBoxBlockNameTitleCenter.Checked;
            int lineNumber = (int)numericUpDownWordLine.Value;
            int wordNumber = (int)numericUpDownWordCount.Value;
            string optionSequence = textBoxBlockOptionSequence.Text.Trim();
            int numberOfQuestions = (int)numericUpDownQuestionCount.Value;
            int startingQuestionNumber = (int)numericUpDownQuestionStart.Value;
            int topicGroupDirection = comboBoxObjectiveItemOrientation.SelectedIndex;
            string subjectiveItemContent = richTextBoxBlockSubjectiveItem.Text;
            bool boldDisplay = checkBoxShowBold.Checked;
            int borderWidth = (int)numericUpDownBlockBoldSize.Value;

            currentOption.AddItem(titleName, titleCenter, lineNumber, wordNumber, optionSequence, numberOfQuestions, startingQuestionNumber, topicGroupDirection, subjectiveItemContent, boldDisplay, borderWidth);
        }
        // 初始化Form组件
        private void InitForm()
        {
            textBoxBlockNameTitle.Text = "";
            checkBoxBlockNameTitleCenter.Checked = false;

            numericUpDownWordLine.Value = 30;
            numericUpDownWordCount.Value = 600;

            textBoxBlockOptionSequence.Text = "A,B,C,D";
            numericUpDownQuestionCount.Value = 1;
            numericUpDownQuestionStart.Value = 1;
            comboBoxObjectiveItemOrientation.SelectedItem = 0;

            richTextBoxBlockSubjectiveItem.Text = "";
            checkBoxShowBold.Checked = false;
            numericUpDownBlockBoldSize.Value = 0;
        }
        // 初始化Form组件
        private void InitForm(BlockOption option)
        {
            textBoxBlockNameTitle.Text = option.TitleName;
            checkBoxBlockNameTitleCenter.Checked = option.TitleCenter;

            numericUpDownWordLine.Value = option.LineNumber;
            numericUpDownWordCount.Value = option.WordNumber;

            textBoxBlockOptionSequence.Text = option.OptionSequence;
            numericUpDownQuestionCount.Value = option.NumberOfQuestions;
            numericUpDownQuestionStart.Value = option.StartingQuestionNumber;
            comboBoxObjectiveItemOrientation.SelectedItem = option.TopicGroupDirection;

            richTextBoxBlockSubjectiveItem.Text = option.SubjectiveItemContent;
            checkBoxShowBold.Checked = option.BoldDisplay;
            numericUpDownBlockBoldSize.Value = option.BorderWidth;

            switch (option.BlockType)
            {
                case (int)BlockTypes.Default:
                    // 可见性设置
                    this.ToolStripStatusLabelDisplay();
                    this.groupBoxOption.Visible = true;
                    this.panelOptionBlockWritting.Visible = false;
                    this.panelOptionBlockObjectiveItem.Visible = false;
                    this.panelOptionBlockSubjectiveItem.Visible = false;
                    this.panelOptionBlockObjectiveItemBold.Visible = false;
                    this.groupBoxOption.Text = this.buttonAddNodeBlock.Text;
                    break;
                case (int)BlockTypes.Objective:
                    this.ToolStripStatusLabelDisplay();
                    this.groupBoxOption.Visible = true;
                    this.groupBoxOption.Text = this.buttonObjectiveItem.Text;
                    this.panelOptionBlockObjectiveItem.Visible = true;
                    this.panelOptionBlockSubjectiveItem.Visible = false;
                    this.panelOptionBlockWritting.Visible = false;
                    break;
                case (int)BlockTypes.Subjective:
                    this.ToolStripStatusLabelDisplay();
                    this.groupBoxOption.Visible = true;
                    this.groupBoxOption.Text = this.buttonSubjectiveItem.Text;
                    this.panelOptionBlockObjectiveItem.Visible = false;
                    this.panelOptionBlockSubjectiveItem.Visible = true;
                    this.panelOptionBlockWritting.Visible = false;
                    this.panelOptionBlockObjectiveItemBold.Visible = true;
                    break;
                case (int)BlockTypes.English:
                    this.ToolStripStatusLabelDisplay();
                    this.groupBoxOption.Visible = true;
                    this.groupBoxOption.Text = this.buttonEnglishWriting.Text;
                    this.panelOptionBlockWritting.Visible = true;
                    this.panelOptionBlockObjectiveItemBold.Visible = false;
                    this.panelOptionBlockObjectiveItem.Visible = false;
                    this.numericUpDownWordCount.Visible = false;
                    break;
                case (int)BlockTypes.Chinese:
                    this.ToolStripStatusLabelDisplay();
                    this.groupBoxOption.Visible = true;
                    this.groupBoxOption.Text = this.buttonChineseWriting.Text;
                    this.panelOptionBlockWritting.Visible = true;
                    this.panelOptionBlockObjectiveItemBold.Visible = false;
                    this.numericUpDownWordCount.Visible = true;
                    this.panelOptionBlockObjectiveItem.Visible = false;
                    break;
            }
        }

        private void TreeViewBlock_AfterSelect(object sender, TreeViewEventArgs e)
        {
            this.currentNode = this.treeViewBlock.SelectedNode;
            string nodeKey = (string)currentNode.Tag;


            if (blockOptionDictionary.ContainsKey(nodeKey))
            {
                currentOption = blockOptionDictionary[nodeKey];
                this.currentNodeKey = nodeKey;

                this.ToolStripStatusLabelDisplay();
                this.InitForm(currentOption);

                this.groupBoxBlockType.Enabled = false;
            }
        }

        /// <summary>
        /// 显示替补状态栏
        /// </summary>
        /// <param name="type"></param>
        private void ToolStripStatusLabelDisplay()
        {
            if (!debug)
            {
                return;
            }
            string text = "[Key='" + this.currentNodeKey + "'][Type='" + this.currentOption.BlockType + "']";
            this.toolStripStatusLabelTool.Text = text;
        }


        private void ButtonPreviewFile_Click(object sender, EventArgs e)
        {
            string filePath = FilePathUtil.DocumentFilePath();
            string examName = textBoxExamName.Text;
            int pageSize = comboBoxPageSize.SelectedIndex;
            int pageOrientation = comboBoxPageOrientation.SelectedIndex;

            GeneratedClass generater = new GeneratedClass();

            generater.FilePath = filePath;
            generater.ExamName = examName;

            switch (pageSize)
            {
                case (int)PageSizeValues.A3:
                    generater.PageSize = PageSizeValues.A3;
                    break;
                case (int)PageSizeValues.A4:
                    generater.PageSize = PageSizeValues.A4;
                    break;
            }
            switch (pageOrientation)
            {
                case (int)PageOrientationValues.Landscape:
                    generater.PageOrientation = PageOrientationValues.Landscape;
                    break;
                case (int)PageOrientationValues.Portrait:
                    generater.PageOrientation = PageOrientationValues.Portrait;
                    break;
            }
            TreeNodeCollection nodes = treeViewBlock.Nodes;

            List<BlockOption> blockOptions = new List<BlockOption>();
            foreach (TreeNode node in nodes)
            {
                string nodeKey = node.Tag.ToString();
                if (blockOptionDictionary.ContainsKey(nodeKey))
                {
                    BlockOption blockOption = blockOptionDictionary[nodeKey];
                    blockOptions.Add(blockOption);
                }
            }
            generater.Create(blockOptions);
            //generater.Create();

            this.toolStripStatusLabelTip.Text = filePath;
            string filepath = toolStripStatusLabelTip.Text;
            LoadFromViewFile(filepath);
            ShowLoadProgressBar();

            if (MessageBox.Show("文件已生成", "提示", MessageBoxButtons.OK, MessageBoxIcon.Question) == DialogResult.OK)
            {
                this.tabControl.SelectedIndex = 1;
                toolStripProgressBar.Visible = false;
            }

        }

        private void Button1_Click(object sender, EventArgs e)
        {
            string dateStamp = DateTimeUtil.DateStampString(DateTime.Now);
            string currentDirectory = Environment.CurrentDirectory.ToString();//获取项目根目录
            string fileDir = currentDirectory + "\\" + dateStamp;
            Process.Start("explorer.exe", fileDir);
        }

        private void ToolStripStatusLabelTip_DoubleClick(object sender, EventArgs e)
        {
            string dateStamp = DateTimeUtil.DateStampString(DateTime.Now);
            string currentDirectory = Environment.CurrentDirectory.ToString();//获取项目根目录
            string fileDir = currentDirectory + "\\" + dateStamp;
            Process.Start("explorer.exe", fileDir);
        }
    }
}
